package com.saas.ability.core.base.http;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class PostEndpoint {
	
	static Logger logger  = LoggerFactory.getLogger(GetEndpoint.class);
	
	public static HttpPost getHttpPost(String url,Map<String,Object> params){
		HttpPost httpPost = new HttpPost(url);
		// 创建参数列表
		if (params != null && !params.isEmpty()) {
			List<NameValuePair> paramList = new ArrayList<>();
			for (String key : params.keySet()) {
				Object val = params.get(key);
				if(val != null){
					paramList.add(new BasicNameValuePair(key, val.toString()));
				}
			}
			try{
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
				httpPost.setEntity(entity);
				return httpPost;
			}catch(Exception e){
				logger.error("生成UrlEncodedFormEntity时失败", e);
				throw new RuntimeException("生成UrlEncodedFormEntity时失败", e);
			}
		}
		return httpPost;
	}
	
	public static HttpPost getHttpPostJSON(String url,Map<String,Object> params){
		HttpPost httpPost = new HttpPost(url);
		// 创建参数列表
		if (params != null && !params.isEmpty()) {
			try{
				httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
				// 解决中文乱码问题
				JSONObject obj = JSONObject.parseObject(JSON.toJSONString(params));
	            StringEntity stringEntity = new StringEntity(obj.toString(), "UTF-8");
	            stringEntity.setContentEncoding("UTF-8");
	            httpPost.setEntity(stringEntity);
				return httpPost;
			}catch(Exception e){
				logger.error("生成UrlEncodedFormEntity时失败", e);
				throw new RuntimeException("生成UrlEncodedFormEntity时失败", e);
			}
		}
		return httpPost;
	}

	public static HttpPost getHttpPostJSON(String url,JSONObject jsonObject){
		HttpPost httpPost = new HttpPost(url);
		// 创建参数列表
		if (jsonObject != null && !jsonObject.isEmpty()) {
			try{
				httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
				// 解决中文乱码问题
				StringEntity stringEntity = new StringEntity(jsonObject.toString(), "UTF-8");
				stringEntity.setContentEncoding("UTF-8");
				httpPost.setEntity(stringEntity);
				return httpPost;
			}catch(Exception e){
				logger.error("生成UrlEncodedFormEntity时失败", e);
				throw new RuntimeException("生成UrlEncodedFormEntity时失败", e);
			}
		}
		return httpPost;
	}
}
